<template>
  <div class="mappp">
      <img 
        :src="noticeEnabled ? require('../../assets/notice.png') : require('../../assets/closeNotice.png')"
        alt="" 
        class="noticeimg" 
        @click="toggleNotice"
      >
      <div class="citySelect">
        <el-select v-model="value" placeholder="请选择" @change="changeSelect" popper-class="selectCity">
          <el-option
            v-for="item in cityList"
            :key="item.id"
            :label="item.district_name"
            :value="item.id">
          </el-option>
        </el-select>
      </div>
    <div id="map" ></div>
    <!-- 报警处理弹窗 -->
   <alert-dialog :dialogVisible="dialogVisible" :currentAlert="currentAlert" @handleClose="handleClose" v-if="dialogVisible" @showProfile="showProfile" @updateAlert="updateAlert"></alert-dialog>
    <!-- 个人信息弹窗 -->
    <profile-dialog :profileDialogVisible="profileDialogVisible" @handleClose2="handleClose2" :user_id="user_id" v-if="profileDialogVisible" ></profile-dialog>
  </div>
  
  
</template>
  
<script>
import alertDialog from '../../components/alertDialog.vue';
import profileDialog from '../../components/profileDialog.vue';
//引入高德地图ui组件
import AMapLoader from '@amap/amap-jsapi-loader';

export default {
  data() {
    return {
      map: null,
      cityList: [],
      value: '',
      noticeEnabled: false, // 默认启用喇叭
      hasNewAlert: false, // 新增是否有新报警标志
      checkAlertTimer: null, // 检查报警定时器
      markerUpdateTimer: null, // 标记点更新定时器
      markerUpdateInterval: 10000, // 15秒更新一次标记点
      markers: [
        // {
        //   status: 'warning',
        //   time: '2025-6-10 16:22:33',
        //   position: [113.66072, 34.79977],
        //   location: '润泽时光里2号楼',
        //   event: '心率预警',
        //   current: 105,
        //   threshold: '75-90'
        // },
        // {
        //   status: 'alert',
        //   time: '2025-6-10 16:25:45',
        //   position: [113.62493, 34.74725],
        //   location: '润泽时光里3号楼',
        //   event: '血压预警',
        //   current: 150,
        //   threshold: '90-120'
        // },
        // {
        //   status: 'warning',
        //   time: '2025-6-10 16:28:12',
        //   position: [113.62954021697999, 34.7461720077045],
        //   location: '润泽时光里1号楼',
        //   event: '血氧预警',
        //   current: 88,
        //   threshold: '95-100'
        // }
      ],
      dialogVisible: false,
      currentAlert: {},
      profileDialogVisible: false,
      user_id: '',
      audio: null,
      
    };
  },
  components: {
    alertDialog,
    profileDialog
  },
  mounted() {
    window._AMapSecurityConfig = { securityJsCode: '1ddc78717b2ef98785a5d08701ff7ae1' };
    this.initAMap();
    this.getCityData();
    
    // 初始化定时器
    this.initMarkerUpdateTimer();
    // this.initCheckAlertTimer();
  },
  beforeDestroy() {
    this.map && this.map.destroy();
    // 清理window上的函数
    window.handleProcess = null;
    // 清除所有定时器
    this.stopAllTimers();
  },
  methods: {
    updateAlert() {
      this.initAMap();
      this.$emit('updateAlert');
    },
    focusMarker(id, type) {
      // 查找对应的标记点，同时匹配id和type
      const markerData = this.markers.find(m => {
        return m.id === id && m.type === type;
      });
      console.log(markerData);
      if (markerData) {
        // 将地图中心移动到标记点位置
        this.map.setCenter(markerData.position);
        // 放大到更合适的级别
        this.map.setZoom(15);
        
        // 查找已创建的标记点对象，允许一定的精度误差
        const marker = this.map.getAllOverlays('marker').find(m => {
          const pos = m.getPosition();
          return pos && 
                 Math.abs(pos.lng - markerData.position[0]) < 0.00001 && 
                 Math.abs(pos.lat - markerData.position[1]) < 0.00001;
        });

        
        if (marker) {
          // 创建信息窗体内容
          let content = "";
          if(markerData.status === 'alert') {
            content = `
              <div class="content-window-card">
                <div class="time"> ${markerData.user_name}</div>
                <div class="time">位置: ${markerData.location}</div>
                <div style="color:${markerData.status === 'alert' ? '#F64646' : '#F68F46'}" class="event">事件: ${markerData.event}</div>
                <div style="display: flex;color:${markerData.status === 'alert' ? '#F64646' : '#F68F46'}">
                  <span class="time" style="margin-right: 10px;">当前值: ${markerData.current}</span>
                  <span class="time">预警范围: ${markerData.threshold}</span>
                </div>
                <div style="text-align:right;">
                  <button style="
                    background:transparent;
                    border:1px solid #11FFD7;
                    color:#11FFD7;
                    padding:4px 8px;
                    border-radius:4px;
                    cursor:pointer;
                  " onclick="window.handleProcess(${JSON.stringify(markerData).replace(/"/g, '&quot;')})">立即处理</button>
                </div>
              </div>
            `;
          } else {
            content = `
              <div class="content-window-card">
                <div class="time">位置: ${markerData.location}</div>
                <div style="color:${markerData.status === 'alert' ? '#F64646' : '#F68F46'}" class="event">事件: ${markerData.event}</div>
                <div style="text-align:right;">
                  <button style="
                    background:transparent;
                    border:1px solid #11FFD7;
                    color:#11FFD7;
                    padding:4px 8px;
                    border-radius:4px;
                    cursor:pointer;
                  " onclick="window.handleProcess(${JSON.stringify(markerData).replace(/"/g, '&quot;')})">立即处理</button>
                </div>
              </div>
            `;
          }
          
          // 创建并打开信息窗体
          const infoWindow = new AMap.InfoWindow({
            content: content,
            offset: new AMap.Pixel(0, -30)
          });
          infoWindow.open(this.map, marker.getPosition());
          
          // 重新设置地图中心点，确保标记点在视图中心
          this.map.setCenter(markerData.position);
        }
      }
    },
    changeSelect(e) {
      console.log('select', e)
      // 向缓存存入城市id
      this.$store.commit('setCityId', e)
      // 重新加载地图数据
      this.initAMap()
    },
     showProfile(e) {
      this.user_id = e.user_id;
      // this.dialogVisible = false;
      this.profileDialogVisible = true;
    },
    handleClose() {
      this.dialogVisible = false;
    },
    handleClose2() {
      this.profileDialogVisible = false;
    },
    // 初始化标记点更新定时器
    initMarkerUpdateTimer() {
      this.updateMarkers(); // 立即更新一次标记点
      this.markerUpdateTimer = setInterval(() => {
        this.updateMarkers();
      }, this.markerUpdateInterval);
    },
    
    // 初始化检查报警定时器
    initCheckAlertTimer() {
      this.checkAlertData(); // 立即检查一次
      this.checkAlertTimer = setInterval(() => {
        this.checkAlertData();
      }, 5000); // 5秒检查一次
    },
    
    // 停止所有定时器
    stopAllTimers() {
      if (this.checkAlertTimer) {
        clearInterval(this.checkAlertTimer);
      }
      if (this.markerUpdateTimer) {
        clearInterval(this.markerUpdateTimer);
      }
    },
    
    // 更新标记点数据
    updateMarkers() {
      this.addMarkers();
    },
    
    // 检查报警数据方法
    checkAlertData() {
      this.$api.mapData({}).then(res => {
        if(res.code == 0 && res.data.length > 0) {
          this.hasNewAlert = true; // 标记有新报警
          // 有新报警数据且喇叭启用时播放提示音
          if(this.noticeEnabled) {
            console.log('播放提示音');
            this.playAlertSound();
          }
        } else {
          this.hasNewAlert = false;
        }
      })
    },
    
    // 新增播放提示音方法
    playAlertSound() {
      const audio = new Audio();
      audio.src = require('../../assets/alert.mp3'); // 请确保项目中有这个音频文件
      audio.play().catch(e => console.error('播放提示音失败:', e));
    },
    
    // 新增切换喇叭状态方法
    toggleNotice() {
      this.noticeEnabled = !this.noticeEnabled;
      // 如果开启喇叭且有新报警，播放提示音
      if(this.noticeEnabled && this.hasNewAlert) {
        this.playAlertSound();
      }
    },
    // 百度坐标转高德坐标
    bdToGd(bdLng, bdLat) {
      const x_PI = 3.14159265358979324 * 3000.0 / 180.0;
      const x = bdLng - 0.0065;
      const y = bdLat - 0.006;
      const z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_PI);
      const theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_PI);
      const gdLng = z * Math.cos(theta);
      const gdLat = z * Math.sin(theta);
      return [gdLng, gdLat];
    },

    addMarkers() {
      this.$api.mapData({}).then(res => {
          if(res.code == 0 && res.data.length > 0) {
            // 报警处理
            this.hasNewAlert = true; // 标记有新报警
            // 有新报警数据且喇叭启用时播放提示音
            if(this.noticeEnabled) {
              console.log('播放提示音');
              this.playAlertSound();
            }

            console.log('89898',res.data)
            // 数据获取成功以后进行循环处理
            let list = res.data.map(item => {
              let longitude = 0;
              let latitude = 0;
              let address = '';
              let min_value = 0;
              let max_value = 0;

              if(item.data.device) {
                // 将百度坐标转换为高德坐标
                [longitude, latitude] = this.bdToGd(
                  Number(item.data.device.longitude),
                  Number(item.data.device.latitude)
                );
                address = item.data.device.address;

              }else {
                longitude = 0;
                latitude = 0;
                address = '';
              }

              if(item.data.merticValue) {
                min_value = item.data.merticValue.min_value;
                max_value = item.data.merticValue.max_value;
              }else {
                min_value = 0;
                max_value = 0;
              }
              

              return {
                id: item.id,
                status: item.type == 1 ? 'alert' : 'warning',
                time: item.alert_time,
                position: [longitude, latitude],
                location: address,
                event: item.type == 1?item.data.merticName:item.data.device.alertName,
                current: parseInt(item.trigger_value),
                threshold: `${min_value}-${max_value}`,
                type: item.type,
                user_name: item.user_name
              }
            })
            this.markers = list;
           
            
            // 如果有标记点数据，将第一个标记点设为地图中心
            if(this.markers.length > 0) {
              this.map.setCenter(this.markers[0].position);
            }
            
            // 循环添加标记点
            this.markers.forEach((markerData, index) => {
              
              const marker = new AMap.Marker({
                position: markerData.position,
                icon: new AMap.Icon({
                  image: require(`../../assets/${markerData.status === 'alert' ? 'err' : 'warn'}.png`),
                  size: new AMap.Size(29, 31)
                }),
                offset: new AMap.Pixel(-14, -20),
                zIndex: index + 1, // 设置zIndex，确保最后一个标记点在最上层
              });

              
              
              // 准备信息窗体内容
              let content = "";
              if(markerData.status === 'alert') {
                content = `
                  <div class="content-window-card">
                    <div class="time"> ${markerData.user_name}</div>
                    <div class="time">位置: ${markerData.location}</div>
                    <div style="color:${markerData.status === 'alert' ? '#F64646' : '#F68F46'}" class="event">事件: ${markerData.event}</div>
                    <div style="display: flex;color:${markerData.status === 'alert' ? '#F64646' : '#F68F46'}">
                      <span class="time" style="margin-right: 10px;">当前值: ${markerData.current}</span>
                      <span class="time">预警范围: ${markerData.threshold}</span>
                    </div>
                    <div style="text-align:right;">
                      <button style="
                        background:transparent;
                        border:1px solid #11FFD7;
                        color:#11FFD7;
                        padding:4px 8px;
                        border-radius:4px;
                        cursor:pointer;
                      " onclick="window.handleProcess(${JSON.stringify(markerData).replace(/"/g, '&quot;')})">立即处理</button>
                    </div>
                  </div>
                `;
              } else {
                content = `
                  <div class="content-window-card">
                    <div class="time">位置: ${markerData.location}</div>
                    <div style="color:${markerData.status === 'alert' ? '#F64646' : '#F68F46'}" class="event">事件: ${markerData.event}</div>
                    <div style="text-align:right;">
                      <button style="
                        background:transparent;
                        border:1px solid #11FFD7;
                        color:#11FFD7;
                        padding:4px 8px;
                        border-radius:4px;
                        cursor:pointer;
                      " onclick="window.handleProcess(${JSON.stringify(markerData).replace(/"/g, '&quot;')})">立即处理</button>
                    </div>
                  </div>
                `;
              }
              
              const infoWindow = new AMap.InfoWindow({
                content: content,
                offset: new AMap.Pixel(0, -30),
                autoMove: false
              });
              
              // 如果是第一个标记点，默认展开信息窗体
              if(index === 0) {
                // console.log('点开第一个标记点', markerData)
                infoWindow.open(this.map, marker.getPosition());
              }
              
              // 点击标记点显示信息窗口
              marker.on('click', () => {
                infoWindow.open(this.map, marker.getPosition());
              });
              
              this.map.add(marker);
            });
            

          } else {
           this.hasNewAlert = false;
         }
      })
    },
    getCityData() {
      this.$api.regionData({}).then(res => {
          if(res.code == 0) {
            // console.log('89898',res.data)
             this.cityList = res.data;
             this.cityList.unshift({
              id: 0,
              district_name: '全部'
            })
          }
      })
    },
    handleProcess(alertData) {
      console.log('处理报警：', alertData)
       this.currentAlert = {
        type: alertData.status === 'alert' ? 'health' : 'safe',
        id: alertData.id,
      };
      this.dialogVisible = true;
    },
    // handleClose(done) {
    //   this.$confirm('确认关闭？未保存的更改将会丢失', '提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   }).then(() => {
    //     done();
    //   }).catch(() => {});
    // },
    initAMap() {
        AMapLoader.load({
          key: "bea7c53db00c5f0d8a3e0b3cf9676042", // 申请好的Web端开发者Key，首次调用 load 时必填
          version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
          plugins: ["AMap.Driving", "AMap.Geocoder"], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
          AMapUI: {
              version: '1.1',
              plugins: [],
          },
        })
        .then((AMap) => {
          // console.log("加载成功",AMap);
          this.map = new AMap.Map("map", {
            // 设置地图容器id
            zoom: 15, // 初始化地图级别
            center: [113.66072, 34.79977], // 初始化地图中心点位置
            mapStyle: 'amap://styles/darkblue',
          });

          // 将处理函数挂载到window对象
          window.handleProcess = (markerData) => {
            this.handleProcess(markerData);
          };

          this.addMarkers(AMap);

          // // 循环添加标记点
          // this.markers.forEach(markerData => {
          //   const marker = new AMap.Marker({
          //     position: markerData.position,
          //     icon: new AMap.Icon({
          //       image: require(`../../assets/${markerData.status === 'alert' ? 'err' : 'warn'}.png`),
          //       size: new AMap.Size(99, 107)
          //     }),
          //     offset: new AMap.Pixel(-20, -20)
          //   });
            
          //   // 添加信息窗口
          //   const content = `
          //       <div class="content-window-card">
          //         <div class="time"> ${markerData.time}</div>
          //         <div class="time">位置: ${markerData.location}</div>
          //         <div style="color:${markerData.status === 'alert' ? '#F64646' : '#F68F46'}" class="event">事件: ${markerData.event}</div>
          //         <div style="display: flex;color:${markerData.status === 'alert' ? '#F64646' : '#F68F46'}">
          //           <span class="time" style="margin-right: 10px;">当前值: ${markerData.current}</span>
          //           <span class="time">预警范围: ${markerData.threshold}</span>
          //         </div>
          //         <div style="text-align:right;">
          //           <button style="
          //             background:transparent;
          //             border:1px solid #11FFD7;
          //             color:#11FFD7;
          //             padding:4px 8px;
          //             border-radius:4px;
          //             cursor:pointer;
          //           " onclick="window.handleProcess(${JSON.stringify(markerData).replace(/"/g, '&quot;')})">立即处理</button>
          //         </div>
          //       </div>
          //     `;

          //   const infoWindow = new AMap.InfoWindow({
          //     content: content,
          //     offset: new AMap.Pixel(0, -30)
          //   });
            
          //   // 点击标记点显示信息窗口
          //   marker.on('click', () => {
          //     infoWindow.open(this.map, marker.getPosition());
          //   });
            
          //   this.map.add(marker);
          // });
          
        })
        .catch((e) => {
          console.log(e);
        });
      
      
    },
  },
};
</script>
<style lang="scss">
.citySelect .el-input__inner {
  background: #333!important;
  border: none!important;
  color: #DCDFE6!important;
}
 .selectCity {
   background: #333!important;
   border: none!important;
}
 .selectCity .el-select-dropdown__item {
  color: #fff!important;
}
 .selectCity .el-select-dropdown__item.hover, .selectCity .el-select-dropdown__item:hover {
  color: #606266!important;
}
 .selectCity .popper__arrow::after {
  border-bottom-color: #333!important;
}
 .selectCity .popper__arrow {
  border-bottom-color: #333!important;
}
.mappp {
  position: relative;
}
#map {
  width: 100%;
  height: 8.625rem;
}
.noticeimg {
  position: absolute;
  left: 0.3rem;
  top: 0.3rem;
  z-index: 99;
  width: 0.5875rem;
  height: 0.5875rem;
  cursor: pointer;
}
.citySelect {
  position: absolute;
  right: 0.5rem;
  top: 0.3rem;
  width: 2.3rem;
  height: 0.35rem;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
  font-size: 0.2rem;
  background: rgba(11, 162, 193, 1);
  z-index: 99;
  .downimg {
    width: 0.106rem;
    height: 0.078rem;
    margin-left: 0.125rem;
  }
}

.content-window-card {
  min-width:230px;
  padding:10px;
  color:#333;
  border-radius:4px;
  .time {
    font-size: 14px;
    font-weight: 400;
    margin-bottom: 8px;
  }
  .event {
    font-size: 14px;
    font-weight: 600;
    margin-bottom: 8px;
  }
}


</style>
<style lang="scss">







// .inputr {
//   width: 198px;
//   height: 39px;
  
// }
// .smallInput {
//   background: #0E4038;
//   height: 39px;
//   line-height: 39px;
//   padding-left: 14px;
//   color: #fff;
//   font-size: 14px;
// }


</style>